package com.sample.springbatch.scheduler;

import com.sample.springbatch.utils.SpringContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

/**
 * Spring Quartz Job实现类
 * DisallowConcurrentExecution 作业不允许并行执行
 * @author zwg
 * @date 2019-05-06 17:20
 **/
@DisallowConcurrentExecution
public class DemoTaskJob implements Job {
    Logger logger = LoggerFactory.getLogger(DemoTaskJob.class);
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        try{
            SchedulerFactoryService.SchedulerInfo schedulerInfo = (SchedulerFactoryService.SchedulerInfo)context.getJobDetail().getJobDataMap().get("jobInfo");

            invokeMethod(schedulerInfo);
        }catch (Exception e){
            logger.error("",e);
        }

    }


    /**
     * 通过反射调用scheduleJob中定义的方法
     *
     * @param scheduleJob
     */
    public void invokeMethod(SchedulerFactoryService.SchedulerInfo scheduleJob) {
        Object object = null;
        Class<?> clazz = null;
        try {
            if (StringUtils.isNotBlank(scheduleJob.getBeanName())) {
                object = SpringContextHolder.getBean(scheduleJob.getBeanName());
            } else if (StringUtils.isNotBlank(scheduleJob.getClassName())) {
                clazz = Class.forName(scheduleJob.getClassName());
                object = clazz.newInstance();
            }
        } catch (Exception e) {
            logger.error("",e);
        }
        if (object == null) {
            logger.error("任务未启动成功，请检查是否配置正确！！！{}",scheduleJob);
            return;
        }
        clazz = object.getClass();
        Method method = null;
        try {
            method = clazz.getDeclaredMethod(scheduleJob.getMethodName());
        } catch (NoSuchMethodException e) {
            logger.error("任务未启动成功，方法名设置错误！！！{}",scheduleJob);
        } catch (SecurityException e) {
            logger.error("",e);
        }
        if (method != null) {
            try {
                method.invoke(object);
            } catch (Exception e) {
                logger.error("",e);
            }
        }
    }
}
